<script setup lang="ts">
  import {
    ref,
    defineEmits,
    computed,
    watch,
    onMounted,
    onUnmounted,
    nextTick,
    reactive,
  } from 'vue';
  import { debounce } from 'lodash-es';
  import { Notification, TableRowSelection } from '@arco-design/web-vue';
  import { useBooleanStore } from '@/store';
  import {
    AOSortingTaskPage,
    materialDistribution,
    bindingWorkBin,
    cleanWaitingTask,
    PackagePerformTask,
    getToolCode,
    getPackCode,
    replaceToolCodeByHand,
    replaceToolCode,
    scanConfirmMaterialList,
    putToolPackage,
    sortStoreRoomIn,
    taskIn,
    saveRemark,
    queryCanReplaceWorkbin,
    insertHcx,
    queryWorkbinMaterial,
    replaceMatchInfo,
  } from '@/api/sorting-matching';
  import ColumnsList from './columns';

  const emit = defineEmits(['updateArray']);
  const booleanStore = useBooleanStore();
  const hStyle = ref({
    'background-color': booleanStore.color,
    'border-radius': booleanStore.borderRadius,
  });
  // 列表头部
  const {
    columns,
    columnsTwo,
    materialOverColumns,
    materialColumns,
    ruleColumns,
  } = ColumnsList();
  const pageSize = ref<number>(10);
  const pageNumber = ref<number>(1);
  // 托盘列表
  const toolDataList = ref<any[]>([]);

  const rowSelection: TableRowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const selectedKeys = ref<any>([]);

  const aoCode = ref<string>('');
  const workpageCode = ref<string>('');
  const planeNo = ref<string>('');
  const palletCode = ref<string>('');
  const station = ref<string>('');
  const visible = ref<boolean>(false);
  const newData = ref<any>();

  // 发送搜索数据
  const flowQueryData = ref({
    aoCode: aoCode.value,
    packageCode: workpageCode.value,
    planeNo: planeNo.value,
    palletCode: palletCode.value,
    station: station.value,
    size: pageSize.value,
    current: pageNumber.value,
  });

  // 表格数据
  async function handleSearch() {
    newData.value = await AOSortingTaskPage(flowQueryData.value);
    emit('updateArray', newData.value);
  }
  const selectedTableData = computed(() => {
    return (
      newData.value?.responseBody?.records?.filter((item: any) =>
        booleanStore.listFour[0]?.value?.includes(item.msAoMatchInfoId)
      ) || []
    );
  });

  function reset() {
    aoCode.value = '';
    workpageCode.value = '';
    planeNo.value = '';
    palletCode.value = '';
    station.value = '';
  }
  // 执行任务
  async function exeTask() {
    // console.log(booleanStore.listFour[0]);
    if (booleanStore.listFour[0]?.value.length !== 1) {
      Notification.warning({
        title: '提示',
        content: '请选择一条数据',
        closable: true,
      });
      return;
    }
    const data = await PackagePerformTask({
      toolCode: selectedTableData.value[0]?.toolCode,
    });
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
      handleSearch();
      booleanStore.toggleBool4(4);
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  }
  // 缓存箱任务下发
  async function taskGoOn() {
    const data = await materialDistribution({});
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  }
  // 增加防抖避免点击多次
  const debouncedTaskGoOn = debounce(taskGoOn, 5000, {
    leading: true, // 立即执行
    trailing: false, // 不在延迟结束后执行
  });
  // 查看缓存箱
  async function lookupHcx() {
    booleanStore.toggleBool2(7);
  }
  // 查询更换托盘箱子
  async function showReplaceToolView() {
    // console.log(selectedTableData.value);

    if (booleanStore.listFour[0]?.value.length !== 1) {
      Notification.warning({
        title: '提示',
        content: '请勾选一条需要更改托盘的数据',
        closable: true,
      });
      return;
    }
    const data = await getToolCode(selectedTableData.value[0]);
    toolDataList.value = data.responseBody || [];
    visible.value = true;
  }
  // 保存托盘更改
  async function replaceToolOk() {
    if (selectedKeys.value.length !== 1) {
      Notification.warning({
        title: '提示',
        content: '请勾选一条托盘数据',
        closable: true,
      });
      return;
    }
    const data = await replaceToolCode({
      sourceToolCode: selectedTableData.value[0]?.toolCode,
      targetToolCode: selectedKeys.value[0],
    });
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
    selectedKeys.value = [];
    visible.value = false;
    booleanStore.toggleBool4(4);
    handleSearch();
  }
  const inputTool = ref<string>('');
  const visible3 = ref<boolean>(false);
  // 手动更改托盘
  async function replaceTool() {
    inputTool.value = '';
    visible3.value = true;
  }
  // 保存手动更改托盘
  async function okSaveTool() {
    if (!inputTool.value.startsWith('21208003')) {
      Notification.warning({
        title: '提示',
        content: '输入的托盘信息不正确',
        closable: true,
      });
      return;
    }
    const data = await replaceToolCodeByHand({
      toolCode: inputTool.value,
      msTaskAoId: selectedTableData.value[0].msTaskAoId,
      msAssginWorkbintoolRelId:
        selectedTableData.value[0].msAssginWorkbintoolRelId,
    });
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
      visible3.value = false;
      selectedKeys.value = [];
      visible.value = false;
      booleanStore.toggleBool4(4);
      handleSearch();
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  }
  // 绑定托盘箱子
  async function bindWorkbinTool() {
    const data = await bindingWorkBin({});
    if (data.message) {
      if (data.retCode === '200') {
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
      } else {
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
      }
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  }

  // 清理等待任务
  async function cleanWaiting() {
    const data = await cleanWaitingTask({});
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  }
  // 查看工作包规则
  const ruleList = ref<any[]>([]);
  const visible4 = ref<boolean>(false);
  async function lookupPackageRule() {
    if (selectedTableData.value.length < 1) {
      Notification.warning({
        title: '提示',
        content: '请至少选择一条数据',
        closable: true,
      });
      return;
    }
    const data = await getPackCode({
      packageCode: selectedTableData.value[0].packageCode,
    });
    if (data.retCode === '200') {
      ruleList.value = data.responseBody;
      visible4.value = true;
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  }
  onMounted(() => {
    handleSearch();
  });
  onUnmounted(() => {
    debouncedTaskGoOn.cancel(); // 清理debounce以防内存泄漏
  });
  // 监听分页
  watch([() => booleanStore.pageNum, () => booleanStore.pageSize], () => {
    if (booleanStore.num5 === 21) {
      pageNumber.value = booleanStore.pageNum;
      pageSize.value = booleanStore.pageSize;
      handleSearch();
    }
  });

  // 扫码操作
  const scanCode = ref<string>('');
  const scanInput = ref<any>('');
  // 适当的时间禁用扫码框
  const disabled = ref<boolean>(false);
  // 托盘编码
  const toolCode = ref<string>('');
  // 缓存箱编码
  const workBinCode = ref<string>('');

  // 检查是否重复扫缓存箱回库
  const scanHcxOper = ref<boolean>(false);
  // 检查是否重复扫工作包回库
  const scanGzbOper = ref<boolean>(false);
  // 重复扫码保存
  const scanSave = ref<boolean>(false);
  // 重复扫码物料
  // const scanMaterialOper = ref<boolean>(false);

  // 托盘物料
  const scanMaterial = ref<any[]>([]);
  // 缓存箱物料
  const hcxinfos = ref<any[]>([]);
  const showHcx = ref<boolean>(false);

  // 控制弹框
  const visible2 = ref<boolean>(false);

  const drawerVisible = ref<boolean>(false);
  // 物料替换
  const replaceVisible = ref<boolean>(false);
  // 输入的备注
  const remark = ref<string>('');
  // 手动更改托盘

  const workBinToolRelId = ref<string>('');

  // 托盘扫码
  async function showToolMatchMaterialInfo() {
    if (toolCode.value === '') {
      if (scanCode.value.length !== 12) {
        Notification.error({
          title: '失败',
          content: '条码格式有误',
          closable: true,
        });
        return;
      }
      toolCode.value = scanCode.value;
    } else {
      toolCode.value = scanCode.value;
      scanMaterial.value = [];
    }
  }

  // 缓存箱扫码
  async function showHcxMatchMaterialInfo() {
    if (scanCode.value.length !== 12) {
      Notification.error({
        title: '失败',
        content: '条码格式有误',
        closable: true,
      });
      return;
    }
    if (toolCode.value === '') {
      Notification.warning({
        title: '提示',
        content: '请先扫托盘',
        closable: true,
      });
      return;
    }
    workBinCode.value = scanCode.value;
    // 扫描一个新的缓存箱的时候清空上一次存储的数据
    scanMaterial.value = [];
    hcxinfos.value = [];
    workBinCode.value = scanCode.value;
    booleanStore.toggleBool(0);
    const data = await scanConfirmMaterialList({
      workbinCode: workBinCode.value,
      toolCode: toolCode.value,
    });

    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: '操作成功',
        closable: true,
      });
      hcxinfos.value = data.responseBody;
      hcxinfos.value = hcxinfos.value.map((item: any) => {
        item.status = '未确认'; // 更新 status
        return item; // 返回更新后的 item
      });
      showHcx.value = true;
    } else {
      Notification.error({
        title: '失败',
        content: '操作失败',
        closable: true,
      });
      workBinCode.value = '';
    }
    booleanStore.toggleBool(0);
  }

  // 分拣保存
  async function savePackage() {
    scanSave.value = false;
    if (workBinCode.value === '' || toolCode.value === '') {
      Notification.warning({
        title: '提示',
        content: '请先扫缓存箱以及托盘',
        closable: true,
      });

      return;
    }
    // 判断托盘下是否存在物料
    if (scanMaterial.value.length < 1) {
      Notification.warning({
        title: '提示',
        content: '请先确认物料',
        closable: true,
      });
      return;
    }
    try {
      // 对数组里面的数据增加一个outQty字段
      scanMaterial.value = scanMaterial.value.map((item) => {
        item.outQty = item.matchQty;
        return item;
      });

      // 存在物料进行分拣
      const data = await putToolPackage({
        toolCode: toolCode.value,
        materialDTOs: scanMaterial.value,
      });
      if (data.retCode === '200') {
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
      } else {
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
      }
      scanSave.value = true;
      booleanStore.toggleBool(0);
    } catch (error) {
      Notification.error({
        title: '失败',
        content: '系统异常，调用超时',
        closable: true,
      });
      booleanStore.toggleBool(0);
    } finally {
      booleanStore.toggleBool(0);
      hcxinfos.value = [];
      scanMaterial.value = [];
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    }
  }

  // 缓存箱回库
  async function workbinBack() {
    if (workBinCode.value === '') {
      Notification.warning({
        title: '提示',
        content: '请先扫缓存箱条码！',
        closable: true,
      });
      return;
    }
    if (scanHcxOper.value) {
      Notification.warning({
        title: '提示',
        content: '请不要重复扫缓存箱回库',
        closable: true,
      });
      return;
    }
    try {
      // 缓存箱回库接口
      const data = await sortStoreRoomIn({ workbinCode: workBinCode.value });
      if (data.retCode === '200') {
        workBinCode.value = '';
        scanHcxOper.value = true;
        hcxinfos.value = [];
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
      } else {
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
      }
    } catch (error) {
      Notification.error({
        title: '失败',
        content: '系统异常，调用超时',
        closable: true,
      });
    }
  }

  // 工作包回库
  async function toolBack() {
    if (toolCode.value === '') {
      Notification.warning({
        title: '提示',
        content: '请先扫工作包条码！',
        closable: true,
      });

      return;
    }
    if (scanGzbOper.value) {
      Notification.warning({
        title: '提示',
        content: '请不要重复扫托盘回库！',
        closable: true,
      });

      return;
    }
    // 当scanSave为false，证明没有输入9005保存
    if (!scanSave.value) {
      Notification.warning({
        title: '提示',
        content: '请先保存物料信息',
        closable: true,
      });

      return;
    }
    try {
      // 调用托盘回库接口
      const data = await taskIn({ palletCode: toolCode.value });
      if (data.retCode === '200') {
        toolCode.value = '';
        scanGzbOper.value = true;
        scanMaterial.value = [];
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
      } else {
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
      }
    } catch (e) {
      Notification.error({
        title: '失败',
        content: '系统异常，调用超时',
        closable: true,
      });
    }
  }

  // 物料确认
  async function materailConfirm() {
    if (scanCode.value === '') {
      Notification.error({
        title: '错误',
        content: '请输入对应的条码格式！',
        closable: true,
      });
      return;
    }

    // 条码的类型
    const barType = ref<string>('');
    // 去除格式的条码
    const scanBarcode = ref('');
    if (scanCode.value.includes('{')) {
      const scanCodeObj: any = JSON.parse(scanCode.value);
      if ('CPHGZ' in scanCodeObj) {
        scanBarcode.value = scanCodeObj.CPHGZ;
        barType.value = 'CP';
      } else {
        scanBarcode.value = scanCodeObj.CKCODE;
        barType.value = 'BJ';
      }
    } else {
      // 85的零件不是纯数字 GW-222222
      scanBarcode.value = scanCode.value;
      barType.value = 'LJ';
    }

    // 在将扫描的条码进行去除格式后判断，条码是否存在
    const barcodeExists = hcxinfos.value.some(
      (item) => item.barcode === scanBarcode.value
    );
    // 如果条码不存在，提示错误并终止操作
    if (!barcodeExists) {
      Notification.error({
        title: '错误',
        content: '扫描条码不存在',
        closable: true,
      });

      return;
    }

    if (barType.value !== 'BZJ') {
      // 定义一个标志变量
      let shouldBreak = false;

      hcxinfos.value.forEach((item) => {
        // if (shouldBreak) return; // 如果标志变量为真，跳过当前循环
        // 当扫描的条码与物料箱下物料条码一致
        if (scanBarcode.value === item.barcode) {
          // 判断托盘是否有物料
          if (scanMaterial.value.length > 0) {
            // 判断托盘里的物料是否与当前扫的物料一致
            const exists = scanMaterial.value.some(
              (item_) => item.msAoMatchInfoId === item_.msAoMatchInfoId
            );
            if (exists) {
              // 如果已经存在，提示并跳出循环
              Notification.warning({
                title: '提示',
                content: `${item.barcode}物料已存在于托盘中`, // 使用模板字符串
                closable: true,
              });
              shouldBreak = true; // 设置标志变量为真
              return;
            }
          }
          // 如果物料不存在于托盘中，加入托盘数组
          scanMaterial.value.push(item);
          item.status = '已确认';
          Notification.success({
            title: '成功',
            content: `${item.barcode}物料确认成功`,
            closable: true,
          });
          // shouldBreak = true; // 设置标志变量为真，跳出循环
        }
      });
    } else {
      // 标准件将所有的默认确认
      hcxinfos.value.forEach((item) => {
        // 检查托盘是否已经有物料
        if (scanMaterial.value.length > 0) {
          // 使用 some 方法检查物料是否已存在
          const exists = scanMaterial.value.some(
            (item_) => item.msAoMatchInfoId === item_.msAoMatchInfoId
          );
          // 如果物料已存在，跳过当前项
          if (exists) {
            return; // 跳过当前项
          }
        }

        // 如果物料不存在于托盘中，加入托盘数组
        scanMaterial.value.push(item);
        // 将物料箱下的数据的状态更改为已确认
        item.status = '已确认';
        // 提示物料确认成功
        Notification.success({
          title: '成功',
          content: `${item.barcode}物料确认成功`, // 使用模板字符串
          closable: true,
        });
      });
    }
  }

  // 扫码操作
  async function scanSubmit() {
    // 托盘扫码
    if (
      new RegExp('^212').test(scanCode.value) &&
      scanCode.value.length >= 11
    ) {
      disabled.value = true;
      showToolMatchMaterialInfo();
      disabled.value = false;
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    } else if (new RegExp('^112').test(scanCode.value)) {
      // 缓存箱扫码
      disabled.value = true;
      showHcxMatchMaterialInfo();
      disabled.value = false;
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    } else if (new RegExp('^312').test(scanCode.value)) {
      // 扫码大件缓存箱子
      disabled.value = true;
      showHcxMatchMaterialInfo();
      disabled.value = false;
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    } else if (scanCode.value === '9005') {
      // 保存
      disabled.value = true;
      savePackage();
      disabled.value = false;
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    } else if (scanCode.value === '9002') {
      disabled.value = true;
      workbinBack();
      disabled.value = false;
      // 箱子回库
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    } else if (scanCode.value === '9004') {
      // 托盘回库
      disabled.value = true;
      toolBack();
      disabled.value = false;
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    } else {
      // 物料确认
      disabled.value = true;
      materailConfirm();
      disabled.value = false;
      // 扫物料码
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    }
  }

  // 修改备注
  function openRemarkView(item: any) {
    remark.value = '';
    workBinToolRelId.value = '';
    remark.value = item.receiveRemark;
    workBinToolRelId.value = item.msAssginWorkbintoolRelId;
    visible2.value = true;
  }

  // 保存备注修改
  async function okSaveRemark() {
    const data = await saveRemark({
      msAssginWorkbintoolRelId: workBinToolRelId.value,
      receiveRemark: remark.value,
    });

    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: '备注修改成功',
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: '备注修改失败',
        closable: true,
      });
    }
    scanCode.value = workBinCode.value;
    showHcxMatchMaterialInfo();
    scanCode.value = '';
    visible2.value = false;
  }

  // 补叫箱子抽屉
  // 缓存箱列表
  const workBinList = ref<any[]>([]);
  // 勾选的缓存箱
  const selected = ref<any[]>([]);
  // 查看可以补叫的箱子列表
  async function showDrawer(item: any) {
    const data = await queryCanReplaceWorkbin(item);
    workBinList.value = data.data;
    drawerVisible.value = true;
  }
  // 补叫箱子
  async function addHcx() {
    // console.log(selected.value);
    if (selected.value.length !== 1) {
      Notification.error({
        title: '失败',
        content: '请勾选一条数据',
        closable: true,
      });
      return;
    }
    const addInfo = workBinList.value.filter((item: any) =>
      selected.value.includes(item.workbinCode)
    );
    const data = await insertHcx(addInfo[0]);
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: '操作成功',
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: '操作失败',
        closable: true,
      });
    }
    selected.value = [];
    scanCode.value = workBinCode.value;
    showHcxMatchMaterialInfo();
    scanCode.value = '';
    drawerVisible.value = false;
  }

  // 查看托盘下的物料信息，主要的列表在pallet-drawer文件
  function searchMaterialInfo() {
    if (toolCode.value === '') {
      return;
    }
    if (workBinCode.value === '') {
      Notification.error({
        title: '失败',
        content: '请扫描缓存箱编号',
        closable: true,
      });
      return;
    }

    booleanStore.setInfo(
      toolCode.value,
      hcxinfos.value[0]?.msTaskPackageId || ''
    );
  }

  // 左右俩测的table数据
  const leftData = ref<any[]>([]);
  const rightData = ref<any[]>([]);
  async function openReplaceView(item: any) {
    replaceVisible.value = true;
    leftData.value = [];
    leftData.value.push(item);
    const data = await queryWorkbinMaterial(item);
    // console.log(data);
    rightData.value = data.data;
  }

  // 调用替换接口
  async function saveReplaceData() {
    const data = await replaceMatchInfo({
      sourceMatch: leftData.value[0],
      replaceMatchList: rightData.value,
    });

    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: '操作成功',
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: '操作失败',
        closable: true,
      });
    }

    scanCode.value = workBinCode.value;
    showHcxMatchMaterialInfo();
    scanCode.value = '';
    replaceVisible.value = false;
  }

  // 初始进入页面
  onMounted(() => {
    nextTick(() => {
      scanInput.value.focus();
    });
  });
</script>

<template>
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">扫码操作</div>
    </template>
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <div>
          <a-input
            ref="scanInput"
            v-model="scanCode"
            :disabled="disabled"
            placeholder="请输入缓存箱/托盘码/条码"
            size="large"
            @keyup.enter="scanSubmit()"
          />
        </div>
      </a-col>
    </a-row>
    <a-row class="margin-top" :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="12">
        <div class="flex-column">
          <div class="flex-box">
            <span>缓存箱编码：</span>
            <span class="font-size">{{ workBinCode }}</span>
          </div>
          <div
            v-for="(item, index) in hcxinfos"
            v-show="showHcx"
            :key="index"
            class="margin-top"
          >
            <a-card :style="{ width: '360px' }" title="缓存箱物料信息">
              <a-list size="small" :split="false">
                <a-list-item style="padding: 0 8px"
                  >条码：<span class="fontSize">{{
                    item.barcode
                  }}</span></a-list-item
                >
                <a-list-item style="padding: 0 8px"
                  >工作包编号：<span class="fontSize">{{
                    item.packageCode
                  }}</span></a-list-item
                >
                <a-list-item style="padding: 0 8px">
                  AO编号：<span class="fontSize">{{
                    item.aoCode
                  }}</span></a-list-item
                >
                <a-list-item style="padding: 0 8px"
                  >所在托盘：<span class="fontSize">{{
                    item.toolCode
                  }}</span></a-list-item
                >
                <a-list-item style="padding: 0 8px"
                  >图号：<span class="fontSize">{{
                    item.itemCode
                  }}</span></a-list-item
                >
                <a-list-item style="padding: 0 8px"
                  >型号：<span class="fontSize">{{
                    item.mProductNumber
                  }}</span></a-list-item
                >
                <a-list-item style="padding: 0 8px"
                  >质量编号：<span class="fontSize">{{
                    item.qualityCode
                  }}</span></a-list-item
                >
                <a-list-item style="padding: 0 8px"
                  >所属单位：<span class="fontSize">{{
                    item.invShop
                  }}</span></a-list-item
                >
                <a-list-item style="padding: 8px 8px"
                  >是否有备注：<span
                    :class="{
                      red: item.receiveRemark === '',
                      green: item.receiveRemark !== '',
                    }"
                    @click="openRemarkView(item)"
                    >{{
                      item.receiveRemark === '' ||
                      item.receiveRemark === null ||
                      item.receiveRemark === undefined
                        ? '未备注'
                        : '有备注'
                    }}</span
                  ></a-list-item
                >
                <a-list-item style="padding: 8px 8px"
                  >待分拣数量：
                  <a-input v-model="item.matchQty" style="width: 50%"> </a-input
                ></a-list-item>
                <a-list-item style="white-space: nowrap; padding: 8px 8px"
                  >是否带证：
                  <a-select v-model="item.isPaper" style="width: 50%">
                    <a-option value="Y">带证</a-option>
                    <a-option value="N">不带证</a-option>
                  </a-select>
                </a-list-item>
                <a-list-item style="padding: 0 8px"
                  >确认状态：
                  <span style="font-size: 18px; font-weight: 600">{{
                    item.status
                  }}</span>
                </a-list-item>
                <a-list-item style="padding: 0 8px">
                  <a-button
                    type="primary"
                    size="large"
                    style="border-radius: 4px"
                    @click="showDrawer(item)"
                    >补叫箱子</a-button
                  >
                  <a-button
                    type="primary"
                    size="large"
                    style="margin-left: 10px; border-radius: 4px"
                    @click="openReplaceView(item)"
                    >更换物料</a-button
                  >
                </a-list-item>
              </a-list>
            </a-card>
          </div>
        </div>
      </a-col>
      <!-- 工作包 -->
      <a-col :span="12">
        <div class="flex-column">
          <div class="flex-box">
            <span>工作包编码：</span>
            <span class="font-size clickable" @click="searchMaterialInfo()">{{
              toolCode
            }}</span>
          </div>
          <div
            v-for="(item, index) in scanMaterial"
            v-show="showHcx"
            :key="index"
            class="margin-top"
          >
            <a-card :style="{ width: '360px' }" title="工作包物料信息">
              <a-list size="small" :split="false" :grid-props="{ padding: 0 }">
                <a-list-item style="padding: 0 8px"
                  >条码：<span class="fontSize">{{
                    item.barcode
                  }}</span></a-list-item
                >
                <a-list-item style="padding: 0 8px">
                  AO编号：<span class="fontSize">{{
                    item.aoCode
                  }}</span></a-list-item
                >
                <a-list-item style="padding: 0 8px"
                  >图号：<span class="fontSize">{{
                    item.itemCode
                  }}</span></a-list-item
                >
                <a-list-item style="padding: 0 8px"
                  >质量编号：<span class="fontSize">{{
                    item.qualityCode
                  }}</span></a-list-item
                >
                <a-list-item style="padding: 0 8px"
                  >数量：<span class="fontSize">{{
                    item.itemQty
                  }}</span></a-list-item
                >
              </a-list>
            </a-card>
          </div>
        </div>
      </a-col>
    </a-row>
  </a-card>
  <!-- 搜索条件 -->
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">查询条件</div>
    </template>

    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <a-input
          v-model="workpageCode"
          placeholder="工作包号"
          size="large"
          allow-clear
        />
      </a-col>
      <a-col :span="6">
        <a-input v-model="aoCode" placeholder="AO号" size="large" allow-clear />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="station"
          placeholder="站位"
          size="large"
          allow-clear
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="planeNo"
          placeholder="架次"
          size="large"
          allow-clear
        />
      </a-col>
    </a-row>

    <a-row class="margin-top" :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <a-input
          v-model="palletCode"
          placeholder="托盘"
          size="large"
          allow-clear
        />
      </a-col>
    </a-row>
    <!-- 按钮操作 -->
    <a-row class="margin-top" :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="24">
        <a-button type="primary" size="large" @click="handleSearch"
          >查询</a-button
        >
        <a-button class="btn-reset" size="large" @click="reset">重置 </a-button>
        <a-button type="primary" class="btn-reset" size="large" @click="exeTask"
          >执行任务
        </a-button>
        <a-button
          type="primary"
          class="btn-reset"
          size="large"
          @click="debouncedTaskGoOn"
          >缓存箱任务下发
        </a-button>
        <a-button
          type="primary"
          class="btn-reset"
          size="large"
          @click="lookupHcx"
          >查看缓存箱
        </a-button>

        <a-button
          type="primary"
          class="btn-reset"
          size="large"
          @click="showReplaceToolView"
          >更换托盘
        </a-button>

        <a-popconfirm
          content="你确定要进行这项操作码?"
          ok-text="确定"
          cancel-text="取消"
          @ok="bindWorkbinTool"
        >
          <a-button type="primary" class="btn-reset" size="large"
            >绑定托盘箱子
          </a-button>
        </a-popconfirm>

        <a-button
          type="primary"
          class="btn-reset"
          size="large"
          @click="cleanWaiting"
          >清理等待任务
        </a-button>
        <a-button
          type="primary"
          class="btn-reset"
          size="large"
          @click="lookupPackageRule"
          >查看工作包规则
        </a-button>
      </a-col>
    </a-row>
  </a-card>
  <!-- 更换托盘 -->
  <a-drawer
    v-model:visible="visible"
    width="auto"
    :footer="false"
    @cancel="() => (visible = false)"
  >
    <template #title> 更换托盘列表 </template>
    <a-space direction="vertical" fill>
      <div style="display: flex; margin-bottom: 5px">
        <a-button type="primary" size="large" @click="replaceToolOk"
          >更改托盘</a-button
        >
        <a-button
          type="primary"
          style="margin-left: 15px"
          size="large"
          @click="replaceTool"
          >手动更改托盘</a-button
        >
      </div>
      <a-table
        v-model:selectedKeys="selectedKeys"
        :stripe="true"
        class="top-table"
        :pagination="false"
        row-key="toolCode"
        :columns="columns"
        :data="toolDataList"
        :row-selection="rowSelection"
      >
      </a-table>
    </a-space>
  </a-drawer>
  <!-- 手动更改托盘 -->
  <a-modal
    v-model:visible="visible3"
    @cancel="() => (visible3 = !visible3)"
    @ok="okSaveTool"
  >
    <template #title> 手动更改托盘 </template>
    <span>请输入托盘:</span>
    <a-textarea v-model="inputTool" size="large" />
  </a-modal>

  <!-- 修改备注 -->
  <a-modal
    v-model:visible="visible2"
    @cancel="() => (visible2 = !visible2)"
    @ok="okSaveRemark"
  >
    <template #title> 修改备注 </template>
    <span>请输入备注:</span>
    <a-textarea v-model="remark" size="large" />
  </a-modal>

  <!-- 补叫箱子抽屉 -->
  <a-drawer
    :width="640"
    :visible="drawerVisible"
    :footer="false"
    unmount-on-close
    @cancel="drawerVisible = !drawerVisible"
  >
    <template #title> 补叫缓存箱 </template>
    <div>
      <a-button
        type="primary"
        size="large"
        style="border-radius: 4px"
        @click="addHcx"
        >补叫箱子</a-button
      >
      <a-table
        v-model:selectedKeys="selected"
        :stripe="true"
        class="top-table"
        :pagination="false"
        :row-selection="rowSelection"
        row-key="workbinCode"
        :columns="columnsTwo"
        :data="workBinList"
        :scroll="{ y: 400 }"
        style="height: 250px"
      >
      </a-table>
    </div>
  </a-drawer>

  <!-- 物料替换 -->
  <a-drawer
    :width="840"
    :visible="replaceVisible"
    :footer="false"
    unmount-on-close
    @cancel="replaceVisible = !replaceVisible"
  >
    <template #title> 物料替换 </template>
    <div>
      <a-button
        type="primary"
        size="large"
        style="border-radius: 4px"
        @click="saveReplaceData"
        >替换</a-button
      >
      <a-row :gutter="8">
        <a-col :span="8">
          <a-table
            :stripe="true"
            class="top-table"
            :pagination="false"
            :columns="materialOverColumns"
            :data="leftData"
            :scroll="{ y: 400 }"
            style="height: 250px"
          >
          </a-table>
        </a-col>
        <a-col :span="16">
          <a-table
            :stripe="true"
            class="top-table"
            :pagination="false"
            :columns="materialColumns"
            :data="rightData"
            :scroll="{ y: 400 }"
            style="height: 250px"
          >
            <template #replaceQty="{ rowIndex }">
              <a-input v-model="rightData[rowIndex].replaceQty" />
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>
  </a-drawer>

  <!-- 查看工作包规则 -->
  <a-drawer
    :width="840"
    :visible="visible4"
    :footer="false"
    unmount-on-close
    @cancel="(visible4 = !visible4), booleanStore.toggleBool4(4)"
  >
    <template #title> 查看工作包规则 </template>
    <div>
      <a-table
        :stripe="true"
        class="top-table"
        :pagination="false"
        :columns="ruleColumns"
        :data="ruleList"
        :scroll="{ y: 400 }"
        style="height: 250px"
      >
      </a-table>
    </div>
  </a-drawer>
</template>

<style scoped>
  .margin-top {
    margin-top: 10px;
  }
  .btn-group {
    float: right;
    margin-top: 15px;
  }

  .btn-reset {
    margin-left: 10px;
  }
  .font {
    font-size: 20px;
    color: black;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue',
      sans-serif;
  }
  .div-tips {
    align-items: center;
    text-align: center;
    color: #999;
  }
  .flex-box {
    display: flex;
    align-items: center;
    white-space: nowrap;
  }
  .top-table {
    white-space: nowrap;
    margin-top: 10px;
  }
  .flex-column {
    display: flex;
    flex-direction: column;
  }
  .font-size {
    font-size: 18px;
    font-weight: bold;
  }
  .red {
    color: red; /* 字体颜色为红色 */
    font-weight: 600;
    background-color: transparent; /* 确保背景颜色为透明 */
    border: 1px solid red;
    border-radius: 8px;
    padding: 3px;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue',
      sans-serif;
  }

  .green {
    color: green; /* 字体颜色为红色 */
    font-weight: 600;
    background-color: transparent; /* 确保背景颜色为透明 */
    border: 1px solid green;
    border-radius: 8px;
    padding: 3px;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue',
      sans-serif;
  }
  .listItem {
    margin: 0;
    padding: 0;
  }
  .fontSize {
    font-weight: 600;
    font-size: 18px;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue',
      sans-serif;
  }
  .margin-top {
    margin-top: 10px;
  }
  .clickable {
    cursor: pointer; /* 鼠标悬停时变成手指 */
    transition: color 0.3s; /* 平滑过渡效果 */
  }

  .clickable:hover {
    color: blue; /* 鼠标悬停时改变字体颜色 */
  }
</style>
